﻿using CoreModule;
using CoreModule.Storages;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Legends;
using OxyPlot.Series;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
namespace IdResourceModule.ViewModels
{
    public class DataStatisticsViewModel : BindableBase,IRegionMemberLifetime
    {
        DbStorage DbStorage { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbStorage"></param>
        public DataStatisticsViewModel(DbStorage dbStorage)
        {
            DbStorage = dbStorage;
        }
        /// <summary>
        /// 
        /// </summary>
        public DateTime? BeingTime { get; set; } = DateTime.Now.AddDays(-7);
        /// <summary>
        /// 
        /// </summary>
        public DateTime? EndTime { get; set; } = DateTime.Now;
        public DataStatisticsViewModel()
        {
            Query();
        }
    
        /// <summary>
        /// 图表Model的mvvm属性，可通知UI更新
        /// </summary>
        public PlotModel DBPChartModel
        {
            get;set;
        }
        public PlotModel SBPChartModel
        {
            get; set;
        }
        public PlotModel PulseRateChartModel
        {
            get; set;
        }
        /// <summary>
        /// 
        /// </summary>
        public PlotModel BpLevelChartModel
        {
            get; set;
        }
        
        public ICommand QueryCommand => new Prism.Commands.DelegateCommand(Query);
        public bool KeepAlive => false;
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public void CreateDBPChartModel()
        {
            var beginTime = this.BeingTime.HasValue ? new DateTime(this.BeingTime.Value.Year,this.BeingTime.Value.Month,this.BeingTime.Value.Day) : new DateTime(2000, 10, 10);
            var endTime = this.EndTime.HasValue ? new DateTime(this.EndTime.Value.Year, this.EndTime.Value.Month, this.EndTime.Value.Day).AddDays(1) : new DateTime(3000, 10, 10);
            var model = new PlotModel
            {
                Title = "收缩压数值分布直方图",
                IsLegendVisible = true
            };
            var maleSeries = new LineSeries { 
                Title = "男", StrokeThickness = 1 ,InterpolationAlgorithm= InterpolationAlgorithms.CanonicalSpline
                ,RenderInLegend=true
               ,TextColor= OxyColor.FromRgb(255,0,0)
            };
            var femaleSeries = new LineSeries {
                Title = "女",  StrokeThickness = 1, InterpolationAlgorithm = InterpolationAlgorithms.CanonicalSpline
                ,
                TextColor = OxyColor.FromRgb(0, 255, 0)
            };
              
            
                var maleItems = DbStorage.MeasurementResultInfos
                    .Where(item=>item.PatientInfo.Sex== SexKind.Male)
                    .Where(item=>item.CreateTime>=beginTime && item.CreateTime<=endTime)
                    .GroupBy(item => item.DBP)
                    .Select(item => new KeyValuePair<int, int>(item.Key, item.Count()))
                    .ToList();
                foreach (var item in maleItems)
                {
                    maleSeries.Points.Add(new DataPoint(item.Key,item.Value));
                }
              
                var femaleItems = DbStorage.MeasurementResultInfos
                   .Where(item => item.PatientInfo.Sex == SexKind.Female)
                   .Where(item => item.CreateTime >= beginTime && item.CreateTime <= endTime)
                  .GroupBy(item => (item.DBP))
                  .Select(item => new KeyValuePair<int, int>(item.Key, item.Count()))
                  .ToList();
                foreach (var item in femaleItems)
                {
                    femaleSeries.Points.Add(new DataPoint(item.Key, item.Value));
                }
                 
          
            var xAxis = new LinearAxis { 
                Position = AxisPosition.Bottom,
                Minimum=60,
                Maximum=210,
                MinimumPadding = 0, 
                MaximumPadding = 0.06,
                AbsoluteMinimum = 0,
                MajorStep = 20,
                MinorStep = 5,
                AbsoluteMaximum=210,
                IsZoomEnabled = false,
            };
            var yAxis = new LinearAxis
            {
                Position = AxisPosition.Left,
                Minimum = 0,
                MinimumPadding = 0,
                MaximumPadding = 0.06,
                AbsoluteMinimum = 0,
            };
            model.Axes.Add(xAxis);
            model.Axes.Add(yAxis);
            model.Series.Add(maleSeries);
            model.Series.Add(femaleSeries);
            var legend = new Legend();
            legend.IsLegendVisible = true;//是否可见
            legend.LegendTitleFontSize = 12; //图例标题字体大小
            legend.LegendFontSize = 12; //图例字体大小
            legend.LegendTitle = "图例";//标题
            legend.LegendFont = "宋体";//图例字体
            legend.LegendFontWeight = FontWeights.Bold;//图例字形
            legend.LegendTextColor = OxyColors.Automatic;
             
            model.Legends.Add(legend);
            this.DBPChartModel = model;
            this.RaisePropertyChanged(nameof(this.DBPChartModel));
        }
        public void CreateSBPChartModel()
        {
            var beginTime = this.BeingTime.HasValue ? new DateTime(this.BeingTime.Value.Year, this.BeingTime.Value.Month, this.BeingTime.Value.Day) : new DateTime(2000, 10, 10);
            var endTime = this.EndTime.HasValue ? new DateTime(this.EndTime.Value.Year, this.EndTime.Value.Month, this.EndTime.Value.Day).AddDays(1) : new DateTime(3000, 10, 10);
            var model = new PlotModel
            {
                Title = "舒张压数值分布直方图",
                IsLegendVisible = true,
                
            };
            var maleSeries = new LineSeries
            {
                Title = "男",
                StrokeThickness = 1,
                InterpolationAlgorithm = InterpolationAlgorithms.CanonicalSpline
                ,
                RenderInLegend = true
               ,
                TextColor = OxyColor.FromRgb(255, 0, 0)
            };
            var femaleSeries = new LineSeries
            {
                Title = "女",
                StrokeThickness = 1,
                InterpolationAlgorithm = InterpolationAlgorithms.CanonicalSpline
                ,
                TextColor = OxyColor.FromRgb(0, 255, 0)
            };
             
          
               
                var maleItems = DbStorage.MeasurementResultInfos
                    .Where(item => item.PatientInfo.Sex == SexKind.Male)
                    .Where(item => item.CreateTime >= beginTime && item.CreateTime <= endTime)
                    .GroupBy(item => item.SBP)
                    .Select(item => new KeyValuePair<int, int>(item.Key, item.Count()))
                    .ToList();
                foreach (var item in maleItems)
                {
                    maleSeries.Points.Add(new DataPoint(item.Key, item.Value));
                }
                var femaleItems = DbStorage.MeasurementResultInfos
                   .Where(item => item.PatientInfo.Sex == SexKind.Female)
                   .Where(item => item.CreateTime >= beginTime && item.CreateTime <= endTime)
                  .GroupBy(item => (item.SBP))
                  .Select(item => new KeyValuePair<int, int>(item.Key, item.Count()))
                  .ToList();
                foreach (var item in femaleItems)
                {
                    femaleSeries.Points.Add(new DataPoint(item.Key, item.Value));
                }
           
            var xAxis = new LinearAxis
            {
                Position = AxisPosition.Bottom,
                Minimum = 40,
                Maximum = 140,
                MinimumPadding = 0,
                MaximumPadding = 0.06,
                AbsoluteMinimum = 0,
                MajorStep = 20,
                MinorStep = 5,
                AbsoluteMaximum = 140,
                IsZoomEnabled = false,
            };
            var yAxis = new LinearAxis
            {
                Position = AxisPosition.Left,
                Minimum = 0,
                MinimumPadding = 0,
                MaximumPadding = 0.06,
                AbsoluteMinimum = 0,
            };
            model.Axes.Add(xAxis);
            model.Axes.Add(yAxis);
            model.Series.Add(maleSeries);
            model.Series.Add(femaleSeries);
            var legend = new Legend();
            legend.IsLegendVisible = true;//是否可见
            legend.LegendTitleFontSize = 12; //图例标题字体大小
            legend.LegendFontSize = 12; //图例字体大小
            legend.LegendTitle = "图例";//标题
            legend.LegendFont = "宋体";//图例字体
            legend.LegendFontWeight = FontWeights.Bold;//图例字形
            legend.LegendTextColor = OxyColors.Automatic;
            model.Legends.Add(legend);
            this.SBPChartModel = model;
            this.RaisePropertyChanged(nameof(this.SBPChartModel));
        }
        /// <summary>
        /// 
        /// </summary>
        public void CreatePulseRateChartModel()
        {
            var beginTime = this.BeingTime.HasValue ? new DateTime(this.BeingTime.Value.Year, this.BeingTime.Value.Month, this.BeingTime.Value.Day) : new DateTime(2000, 10, 10);
            var endTime = this.EndTime.HasValue ? new DateTime(this.EndTime.Value.Year, this.EndTime.Value.Month, this.EndTime.Value.Day).AddDays(1) : new DateTime(3000, 10, 10);
            var model = new PlotModel
            {
                Title = "脉率分布直方图",
                IsLegendVisible = true,
                
            };
            var maleSeries = new LineSeries
            {
                Title = "男",
                StrokeThickness = 1,
                InterpolationAlgorithm = InterpolationAlgorithms.CanonicalSpline
                ,
                RenderInLegend = true,
               
            
                TextColor = OxyColor.FromRgb(255, 0, 0)
            };
            var femaleSeries = new LineSeries
            {
                Title = "女",
                StrokeThickness = 1,
                InterpolationAlgorithm = InterpolationAlgorithms.CanonicalSpline
                ,
                TextColor = OxyColor.FromRgb(0, 255, 0)
            };
           
         
                var maleItems = DbStorage.MeasurementResultInfos
                    .Where(item => item.PatientInfo.Sex == SexKind.Male)
                    .Where(item => item.CreateTime >= beginTime && item.CreateTime <= endTime)
                    .GroupBy(item => item.PulseRate)
                    .Select(item => new KeyValuePair<int, int>(item.Key, item.Count()))
                    .ToList();
                foreach (var item in maleItems)
                {
                    maleSeries.Points.Add(new DataPoint(item.Key, item.Value));
                }
                var femaleItems = DbStorage.MeasurementResultInfos
                   .Where(item => item.PatientInfo.Sex == SexKind.Female)
                   .Where(item => item.CreateTime >= beginTime && item.CreateTime <= endTime)
                  .GroupBy(item => (item.PulseRate))
                  .Select(item => new KeyValuePair<int, int>(item.Key, item.Count()))
                  .ToList();
                foreach (var item in femaleItems)
                {
                    femaleSeries.Points.Add(new DataPoint(item.Key, item.Value));
                }
       
            var xAxis = new LinearAxis
            {
                Position = AxisPosition.Bottom,
                Minimum = 40,
                Maximum = 140,
                MinimumPadding = 0,
                MaximumPadding = 0.06,
                AbsoluteMinimum = 0,
                MajorStep = 20,
                MinorStep = 5,
                AbsoluteMaximum = 140,
                IsZoomEnabled = false,
            };
            var yAxis = new LinearAxis
            {
                Position = AxisPosition.Left,
                Minimum = 0,
                MinimumPadding = 0,
                MaximumPadding = 0.06,
                AbsoluteMinimum = 0,
            };
            model.Axes.Add(xAxis);
            model.Axes.Add(yAxis);
            model.Series.Add(maleSeries);
            model.Series.Add(femaleSeries);
            var legend = new Legend();
            legend.IsLegendVisible = true;//是否可见
            legend.LegendTitleFontSize = 12; //图例标题字体大小
            legend.LegendFontSize = 12; //图例字体大小
            legend.LegendTitle = "图例";//标题
            legend.LegendFont = "宋体";//图例字体
            legend.LegendFontWeight = FontWeights.Bold;//图例字形
            legend.LegendTextColor = OxyColors.Automatic;
            model.Legends.Add(legend);
             
            this.PulseRateChartModel = model;
            this.RaisePropertyChanged(nameof(this.PulseRateChartModel));
        }
       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="barSeries"></param>
        /// <param name="sexKind"></param>
        public void AddBpLevelBarItems( DateTime beginTime,DateTime endTime, SexKind sexKind, BarSeries barSeries)
        {
 
                var maleNormalCount = DbStorage.MeasurementResultInfos
                    .Where(item => item.CreateTime >= beginTime && item.CreateTime <= endTime)
                    .Where(item => item.PatientInfo.Sex == sexKind && item.BpLevel == PressureLevel.Normal)
                    .Count();
                barSeries.ActualItems.Add(new BarItem(maleNormalCount, -1));
               
                
                var maleHigh1Count = DbStorage.MeasurementResultInfos
                 .Where(item => item.CreateTime >= beginTime && item.CreateTime <= endTime)
                 .Where(item => item.PatientInfo.Sex == sexKind && item.BpLevel == PressureLevel.High1)
                 .Count();
                barSeries.ActualItems.Add(new BarItem(maleHigh1Count, -1));
                var maleHigh2Count = DbStorage.MeasurementResultInfos
                .Where(item => item.CreateTime >= beginTime && item.CreateTime <= endTime)
                .Where(item => item.PatientInfo.Sex == sexKind && item.BpLevel == PressureLevel.High2)
                .Count();
                barSeries.ActualItems.Add(new BarItem(maleHigh2Count, -1));
                var maleHigh3Count = DbStorage.MeasurementResultInfos
               .Where(item => item.CreateTime >= beginTime && item.CreateTime <= endTime)
               .Where(item => item.PatientInfo.Sex == sexKind && item.BpLevel == PressureLevel.High3)
               .Count();
                barSeries.ActualItems.Add(new BarItem(maleHigh3Count, -1));
                var maleJustHighCount = DbStorage.MeasurementResultInfos
             .Where(item => item.CreateTime >= beginTime && item.CreateTime <= endTime)
             .Where(item => item.PatientInfo.Sex == sexKind && item.BpLevel == PressureLevel.JustHigh)
             .Count();
                barSeries.ActualItems.Add(new BarItem(maleJustHighCount, -1));
            
        }
        /// <summary>
        ///    SaveBitmap(sender as PlotView, "性别.png");
        /// </summary>
        public void CreateBpLevelChartModel()
        {
            var beginTime = this.BeingTime.HasValue ? this.BeingTime.Value : new DateTime(2000, 10, 10);
            var endTime = this.EndTime.HasValue ? this.EndTime.Value.AddDays(1) : new DateTime(3000, 10, 10);
            var plotModel1 = new PlotModel();
            plotModel1.Title = "血压分级直方图";
            var xAxis = new CategoryAxis();
            xAxis.LabelField = "Label";
            xAxis.Key = "y";
            xAxis.MinorStep = 1;
            xAxis.IsZoomEnabled = false;
            xAxis.ActualLabels.Add(PressureLevel.Normal.GetDescription());
          
            xAxis.ActualLabels.Add(PressureLevel.High1.GetDescription());
            xAxis.ActualLabels.Add(PressureLevel.High2.GetDescription());
            xAxis.ActualLabels.Add(PressureLevel.High3.GetDescription());
            xAxis.ActualLabels.Add(PressureLevel.JustHigh.GetDescription());
            var yAxis = new LinearAxis();
            yAxis.AbsoluteMinimum = 0;
            yAxis.Key = "x";
            yAxis.MinimumPadding = 0;
            plotModel1.Axes.Add(xAxis);
            plotModel1.Axes.Add(yAxis);
            var maleSeries = new BarSeries()
            {
                RenderInLegend = true,
            };
            maleSeries.FillColor = OxyColor.FromArgb(255, 78, 154, 6);
            maleSeries.ValueField = "Value1";
            maleSeries.XAxisKey = "x";
            maleSeries.YAxisKey = "y";
            maleSeries.Title = "男";
            var femaleSeries = new BarSeries()
            {
                RenderInLegend = true,
            };
            femaleSeries.FillColor = OxyColor.FromArgb(255, 200, 141, 0);
            femaleSeries.ValueField = "Value2";
            femaleSeries.XAxisKey = "x";
            femaleSeries.YAxisKey = "y";
            femaleSeries.Title = "女";
            AddBpLevelBarItems(beginTime,endTime, SexKind.Male, maleSeries);
            AddBpLevelBarItems(beginTime, endTime, SexKind.Female, femaleSeries);
             
            plotModel1.Series.Add(maleSeries);
            plotModel1.Series.Add(femaleSeries);
            var legend = new Legend();
            legend.IsLegendVisible = true;//是否可见
            legend.LegendTitleFontSize = 12; //图例标题字体大小
            legend.LegendFontSize = 12; //图例字体大小
            legend.LegendTitle = "图例";//标题
            legend.LegendFont = "宋体";//图例字体
            legend.LegendFontWeight = FontWeights.Bold;//图例字形
            legend.LegendTextColor = OxyColors.Automatic;
            plotModel1.Legends.Add(legend);
  
            this.BpLevelChartModel = plotModel1;
            this.RaisePropertyChanged(nameof(this.BpLevelChartModel));
        }
        /// <summary>
        /// 
        /// </summary>
        public void Query()
        {
            CreateDBPChartModel();
            CreateSBPChartModel();
            CreatePulseRateChartModel();
            CreateBpLevelChartModel();
             
        }
    }
}
